package cn.smbms.controller;

import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pojo.Role;
import cn.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.tools.Constants;
@Controller
@RequestMapping("role")
public class RoleController {
	@Autowired
	private RoleService rsi;
	
	@RequestMapping("list.html")
	public String getRoleList(Model model) {
		model.addAttribute("roleList", rsi.getRoleList());
		return "rolelist";
	}
	
	@RequestMapping("toUp")
	public String toUp(Model model,String id){
		model.addAttribute("role",rsi.getRoleById(id));
		return "rolemodify";
	}
	
	@RequestMapping("saveUp")
	public String saveUp(Role role,HttpSession se){
		User user=(User)se.getAttribute(Constants.USER_SESSION);
		role.setModifyBy(user.getId());
		role.setModifyDate(new Date());
		if(rsi.upRole(role)>0){
			return "redirect:/role/list.html";
		}
		return "rolemodify";
	}
	
	@RequestMapping("del")
	@ResponseBody
	public Object del(String id){
		HashMap<String,String> resultMap=new HashMap<String,String>();
		String result="notexist";
		int num=rsi.delBill(id);
		if(num>0){
			result="true";
		}else if(num<0){
			result="false";
		}
		resultMap.put("delResult", result);
		return resultMap;
	}
	
	@RequestMapping("add.html")
	public String toAdd(){
		return "roleadd";
	}
	
	@RequestMapping("Code")
	@ResponseBody
	public Object getCode(String code){
		HashMap<String,String> resultMap=new HashMap<String,String>();
		String result="notexist";
		int num=rsi.getRoleByCode(code);
		if(num>0){
			result="exist";
		}else{
			result="notexist";
		}
		resultMap.put("roleCode", result);
		return resultMap;
	}
	
	@RequestMapping("saveAdd")
	public String saveAdd(Role role,HttpSession se){
		User user=(User)se.getAttribute(Constants.USER_SESSION);
		role.setCreatedBy(user.getId());
		role.setCreationDate(new Date());
		if(rsi.addRole(role)>0){
			return "redirect:/role/list.html";
		}
		return "roleadd";
	}
	
}
